import {
	uniBack,
	uniCall,
	uniModal,
	uniNavigate
} from '@/utils/uniPromise';
import {
	formatStockList
} from '@/module/product/prodMet';
export const orderjs = {
	data() {
		return {
			currentOrderItem: {},
			isBalance: true,
			business_appid: ''
		}
	},
	computed: {
		checkBtn(item, btnIndex) {
			return (item, btnIndex) => {
				let val = false;
				let state = item.pay_status;
				switch (btnIndex) {
					case -1: // 取消订单
						if (state == 0 || state == -1 || state == '12') val = true;
						break;
					case 0: // 立即支付
						if (state == 0 || state == '12') val = true;
						break;
					case 1: //核销    
						// if (this.vuex_business.order_qrcode == 1 && state == '1' && [1, 2, 3, 7,17].includes(item
						if (state == '1' && [1, 2, 3, 7,17].includes(item.type) && (item.detailed[0].fk_product_id > 0 || item.detailed[0].fk_pro_id >
								0)) val = true
						break;
					case 2: // 申请退款
						if (state == '1' && (item.type != '6' && item.type != '5' && item.type != '8' && item
								.type != '11' && item.type != '12')) {
							if (item.type !== '9' || item.is_group == 1) {
								val = true
							}
						}
						break;
					case 3: // 查看物流
						if (item.express_count > 0) val = true;
						break;
					case 4: // 评价
						if (state == '5' && item.is_comment <= 0 && item.type != '10' && item.type != '11' && (
								item.refund_status == '0' || item.refund_status == '3')) val = true
						break;
					case 5: // 确认收货
						if (state == 4 && item.express_no) val = true;
						break;
					case 6: // 邀请好友
						if (state == '1' && item.type == '9' && item.is_group != '1') val = true;
						break;
					case 7: // 拨打客服
						if ((state == '4' || state == '7') && this.vuex_business.custom_tel) val = true;
						break;
					case 8: // 继续点餐，餐饮
						if (state == '12') val = true;
						break;
				}
				return val;
			};
		},
		// 判断是否可以修改订单地址号码那些
		judegAddressinUserinfo(item) {
			return function(item) {

				let {
					pay_status,
					type
				} = item
				if ((pay_status == 1 || pay_status == 0) && Array.isArray(item.detailed) && item.detailed[0]
					.fk_product_id > 0) {
					return true
				} else {
					return false
				}


			}
		},
		// 判断订单能否全部退款
		productRefund(data) {
			return function(data) {
				let {
					type,
					detailed
				} = data
				// fk_pro_id是详情页的
				let detailJudeg = Array.isArray(detailed) && detailed[0] && (detailed[0].fk_product_id > 0 ||
						detailed[0].fk_pro_id > 0) ?
					true : false

				if (data.total_amount <= 0) {
					return false
				} else if (type == 1 && detailJudeg) { // 普通商品订单
					// 已支付/已发货、订单退款状态是可退款(0/3)、detailed里的产品都必须能退款(s_refund == 1)、detailed不能包含退款中/已退款
					let judeg = true
					detailed.forEach(el => {
						if (el.refund_status == 1 || el.refund_status == 2 || el.refund_status == 4 ||
							el.is_refund != 1) {
							judeg = false
						}
					})
					return judeg && (data.pay_status == 1 || data.pay_status == 4) && (data.refund_status ==
						'0' || data.refund_status ==
						'3') ? true : false
				} else {
					// 其他订单
					// 已支付、订单退款状态是可退款(0/3)、detailed里的第一个商品是可退款的（is_refund == 1）
					if ( detailJudeg && type == 17 && data.pay_status == 1 && (data
							.refund_status == '0' || data.refund_status == '3')) {
						return true
					} else if (detailJudeg && detailed[0].is_refund == 1 && data.pay_status == 1 && (data
							.refund_status == '0' || data.refund_status == '3')) {
						return true
					} else if(type == 9 && data.pay_status > 0  && data.pay_status != 2 && data.pay_status != 3){
						return true
					}else {
						return false
					}
				}
			}
		},
		overtime(time) {
			let day = 864000000
			let timestamp = new Date().getTime()
			return (time) => {
				let timeend = new Date(time).getTime()
				return timestamp - timeend < day
			}
		}
	},
	filters: {
		statusFilter(item) {
			let state = item.pay_status;
			let type = item.type
			let val = '';
			switch (state) {
				case -1:
				case '-1':
					val = '已关闭';
					break;
				case 0:
				case '0':
					val = '未支付';
					break;
				case 1:
					if (type == 4) {
						val = '待出游'
					} else if (type == 3) {
						val = '待入住'
					} else if (type == 5) {
						val = '已购买'
					} else if (type == 9) {
						val = item.is_group == 1 ? '拼团成功，待发货' : '拼团中'
					} else if (type == 2) {
						val = '待使用'
					} else if (type == 7) {

						val = (item.detailed[0].fk_product_id > 0 || item.detailed[0].fk_pro_id > 0) ? '准备中' : '已收款'
					} else {
						val = '待发货'
					}
					break;
				case 2:
					val = item.order_refund_count > 0 && item.detailed.length > item.order_refund_count ? '部分退款' :
						'退款审核中'
					break;
				case 3:
					val = '已退款';
					break;
				case 4:
					val = '已发货';
					break;
				case 5:
					val = '已收货';
					break;
				case 6:
					val = '待确认'; // 酒店,目前不支持：酒店下单后先变成6，等酒店确认后再变成待支付，然后才允许 用户支付
					break;
				case 7:
					val = '已拒单'; // 酒店
					break;
				case 8:
					val = '已入住'; // 酒店
					break;
				case 9:
					val = '已确认';
					break;
				case 10:
					val = '已完成';
					break;
				case 88:
					val = '待收货';
					if (item.ticket_status == 2) {} else {
						val = '核销完成';
					}
					if (item.pay_status == 10) val = '已完成';
					break;
			}
			return val;
		},
	},
	methods: {
		// 取消订单
		$onCancel(id, index, type) {
			let str = '取消后将从订单列表中移除'
			if (type == 14) {
				str = '取消后保证金将无法退还'
			}
			uniModal({
				title: '取消订单',
				content: str
			}).then(() => {
				this.$loading('正在删除');
				this.$resPost('DeleteOrderInfo', {
						pk_id: id
					})
					.then(() => {
						this.$hide();
						this.$toast({
							title: '成功',
							icon: 'success'
						});
						this.dataList.splice(index, 1);
					})
					.catch(() => {
						this.$hide();
						this.$toast('订单取消失败');
					});
			});
		},
		// 选择支付方式
		$onPayOrder(item, pageType) {
			let isBalance = true
			if (item.type == 1) {
				item.detailed.forEach((item) => {
					if (item.business_pro_id > 0) {
						isBalance = false
					}
				})
			}
			this.isBalance = isBalance

			this.currentOrderItem = {
				...item,
				pageType: pageType || 2, // 1:列表 2：详情页
			}
			this.business_appid = item.business_appid
			// #ifdef APP-PLUS
			// // 总有趣app
			// if(item.business_appid == '2021002146652650'){
			// 	this.$refs.payCheck.payClass = 7
			// 	this.$refs.payCheck.payChange('zhifubao')
			// }else{
			// 	this.$refs.payCheck.payChange('wx')
			// 	this.$refs.payCheck.payClass = this.$refs.payCheck.list[0].value
			// }
			// #endif
			if (this.currentOrderItem.type == 14) {
				this.auctionOrderPay()
				return
			} else {
				this.$refs.payCheck.open(item.total_amount)
			}
		},
		$onOrder(id) {
			let table_id = uni.getStorageSync('vuex_table_id')
			let restaurantInfo = JSON.parse(uni.getStorageSync('restaurantInfo'))
			this.$linkTo(
				`/package/restaurant/take-out/index?meal_id=${restaurantInfo.pk_id}&id=${table_id}&order_id=${id}`
			)
		},
		// 开始支付
		onPayPrice(obj) {
			let pay_type = obj.pay_type
			let updateParams = {}
			if (obj.business_appid) {
				updateParams.business_appid = obj.business_appid
			}
			this.$loading()
			if (this.currentOrderItem.coupon > 0 && pay_type == 6) {
				pay_type = 1
			}
			let opts = {
				totalPrice: this.currentOrderItem.total_amount, // 支付金额
				order_type: this.currentOrderItem.type, // 订单类型
				remark: '商品订单', // 余额扣款备注
				updateApi: 'UpdateOrderStatus', // 更新接口
				pay_type: pay_type || 1, // 支付方式
				integral: this.currentOrderItem.type == 8 ? true : false, // 是否积分订单
				updateParams: {
					...updateParams
				}
			}
			this.setSubMsg().then(() => {
				this.judgeTypeToPay({
					pk_id: this.currentOrderItem.pk_id,
					order_no: this.currentOrderItem.order_no,
					bill_type: obj.bill_type
				}, opts).then(() => {
					this.$hide()
					this.$toast({
						title: '支付成功',
						icon: 'success'
					});
					this.$initPage();
				}).catch(err => {
					this.$hide()
					if (err) {
						this.$toast({
							title: err
						})
					}
				})
			})
		},
		auctionOrderPay() {
			this.$loading();
			let id = this.currentOrderItem.pageType == 1 ? this.currentOrderItem.detailed[0].fk_product_id :
				this.currentOrderItem.detailed[0].product_id
			let name = this.currentOrderItem.pageType == 1 ? this.currentOrderItem.detailed[0].detailed_name :
				this.currentOrderItem.detailed[0].name
			this.$resPost('GetAuctionProductDetailed', {
				pk_id: id
			}).then(({
				data
			}) => {
				let obj = {
					product_img: data.logo,
					express_num: data.express_num, // 多少起免邮费
					express_price: data.express_price, // 快递费用
					product_freight: data.product_freight || [], // 运费模板
					num: 1,
					price: this.currentOrderItem.detailed[0].price,
					product_id: data.pk_id,
					product_name: data.name,
					standard: name, // 库存名称
					service_charge: this.currentOrderItem.detailed[0].service_charge || 0
				};
				let str =
					`/package/product/dutchAuction/order?order_id=${this.currentOrderItem.pk_id}&order_no=${this.currentOrderItem.order_no}&goBack=1`
				if (this.currentOrderItem.coupon > 0) {
					str += `&coupon=${this.currentOrderItem.coupon}`
				}





				// #ifdef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
				this.$emit('callbackData', {
					type: 'prod',
					list: [{
						...obj
					}]
				})
				this.$to(str)
				// #endif

				// #ifndef MP-ALIPAY || MP-BAIDU || MP-TOUTIAO
				uniNavigate(
					str
				).then(res => {
					this.$hide();
					res.eventChannel.emit('acceptParams', {
						type: 'prod',
						list: [{
							...obj
						}]
					});
				});
				// #endif
			})
		},
		/**
		 * 检测当前商品是否有库存，仅支持特产
		 * @param prodId prodId 产品id
		 * @param stockNum 购买数量
		 * @param stockId 库存id
		 * @returns {Promise<unknown>}
		 */
		$checkProdStock(prodId, stockNum, stockId) {
			return new Promise((resolve, reject) => {
				this.$loading();
				this.$resPost('GetProductDetailed', {
						pk_id: prodId
					})
					.then(({
						data
					}) => {
						if (!data.pk_id) return Promise.reject();
						this.$hide();
						data.stock_list = formatStockList(data.stock_list, false);
						if (data.stock_list.length > 0) {
							let stockItem = data.stock_list.find(item => item.pk_id === stockId);
							if (stockItem) {
								if (stockItem.max_num >= stockNum) {
									resolve(false);
								} else {
									this.$toast('库存不足');
									reject(true);
								}
							} else {
								this.$toast('库存不足');
								reject(true);
							}
						} else {
							this.$toast('库存不足');
							reject(true);
						}
					})
					.catch(() => {
						this.$toast('未获取到产品信息');
						reject(true);
					});
			});
		},
		// 跳转到核销二维码
		$onValidate(item) {
			this.$to(`/package/order/validate?id=${item.pk_id}&orderNo=${item.order_no}`);
		},
		// 申请退款
		$openRefund(item) {
			// this.$refs.applyRefundRef.show(item);
			this.$linkTo(`/package/order/refund/refundDetail?id=${item.pk_id}&order_no=${item.order_no}`)
		},
		// 跳转到物流详情页
		$linkToLogistic(item) {
			if (item.detailed.length > 1) {
				this.$to(`/package/order/logistic/logisticList?id=${item.pk_id}`)
			} else {
				this.$to(
					`/package/order/logistic?id=${item.pk_id}&express_no=${item.express_no}&express=${item.express}&express_name=${item.express_name}`
				);
			}
		},
		// 确认收货
		$confirmGood(item) {
			uniModal({
				title: '确认收货',
				content: '是否确认收货'
			}).then(() => {
				this.$loading('正在提交');
				this.$resPost('UpdateSignFOROrder', {
						order_no: item.order_no
					})
					.then(() => {
						this.$toast('提交成功');
						this.$initPage();
					})
					.catch(() => {
						this.$toast('提交失败');
					});
			});
		},
		// 邀请
		$invite(item, isDetail) {
			let fk_teambuy_id = isDetail ? item.detailed[0].fk_teambuy_id : item.fk_teambuy_id
			let guid = isDetail ? item.detailed[0].guid : item.guid
			this.$linkTo(`/package/product/group/share-details/index?id=${fk_teambuy_id}&guid=${guid}`)
		},
		// 拨打客服电话
		$callContact() {
			// #ifdef H5
			uniCall(this.vuex_business.custom_tel);
			// #endif
		},
	}
}
